package cn.dwong.msgGateway.controller;

import cn.dwong.msgGateway.base.ApiResponse;
import cn.dwong.msgGateway.entity.TitleContent;
import cn.dwong.msgGateway.service.GatewayService;
import cn.dwong.msgGateway.service.MessageService;
import cn.dwong.msgGateway.service.UserService;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * @author 73202
 * @date 2022/3/9 20:44
 */
@RestController
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private GatewayService gatewayService;



    @PostMapping("/directmessage")
    public ApiResponse directMessage(@Valid @RequestBody TitleContent titleContent,
                                     @Pattern(regexp = "^[1][3,4,5,6,7,8,9][0-9]{9}$") @RequestParam String tels,
                                     @RequestParam String qos,
                                     @RequestParam String userName,
                                     @RequestParam String sessionId,
                                     BindingResult result){
        if (result.hasErrors()){
            return ApiResponse.ofBadRequest();
        }
        //校验是否登录
        if (!messageService.checkSessionId(userName,sessionId)){
            return ApiResponse.ofUnauthorized();
        }
        //发送短信
//        String resCode = messageService.sendMsg(qos,tels,titleContent);
        String resCode  = gatewayService.requestRateLimiterThreadPool(tels,qos,sessionId,titleContent);
//        String resCode  = gatewayService.requestRateLimiter(tels,qos,sessionId,titleContent);

        if (resCode != null){
            if (resCode.equals("0")){
                return ApiResponse.ofSuccess();
            } else if (resCode.equals("400")){
                return ApiResponse.ofBadRequest();
            } else if (resCode.equals("500")){
                return ApiResponse.ofInterNalServerError();
            } else if (resCode.equals("409")){
                return ApiResponse.ofInterNalServerError();
//                return ApiResponse.ofCurrentlimiting();
            } else if(resCode.equals("429")){
//                return ApiResponse.ofCutoff();
                return ApiResponse.ofInterNalServerError();
            }else {
                return ApiResponse.ofInterNalServerError();
            }
        }else {
            return ApiResponse.ofInterNalServerError();
        }
    }
}
